<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Excel导出调试测试</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        button { padding: 10px 20px; margin: 10px; font-size: 16px; }
        .result { margin: 20px 0; padding: 10px; border: 1px solid #ccc; }
        .success { background-color: #d4edda; border-color: #c3e6cb; }
        .error { background-color: #f8d7da; border-color: #f5c6cb; }
        table { border-collapse: collapse; margin: 20px 0; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background-color: #f8f9fa; }
    </style>
</head>
<body>
    <h1>Excel导出调试测试</h1>
    
    <div>
        <button onclick="testXLSXLoad()">1. 测试XLSX库加载</button>
        <button onclick="testSimpleExport()">2. 测试简单导出</button>
        <button onclick="testComplexExport()">3. 测试复杂数据导出</button>
    </div>
    
    <div id="result" class="result"></div>
    
    <h3>测试数据表格：</h3>
    <table id="testTable">
        <thead>
            <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>邮箱</th>
                <th>部门</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>张三</td>
                <td>25</td>
                <td>zhangsan@test.com</td>
                <td>技术部</td>
            </tr>
            <tr>
                <td>李四</td>
                <td>30</td>
                <td>lisi@test.com</td>
                <td>产品部</td>
            </tr>
            <tr>
                <td>王五</td>
                <td>28</td>
                <td>wangwu@test.com</td>
                <td>设计部</td>
            </tr>
        </tbody>
    </table>

    <script>
        // 动态加载XLSX库的函数
        function loadXLSX() {
            return new Promise((resolve, reject) => {
                if (typeof XLSX !== 'undefined') {
                    resolve(XLSX);
                    return;
                }

                const script = document.createElement('script');
                script.src = './xlsx.full.min.js';
                script.onload = () => {
                    if (typeof XLSX !== 'undefined') {
                        console.log('XLSX库加载成功');
                        resolve(XLSX);
                    } else {
                        reject(new Error('XLSX库加载后仍然未定义'));
                    }
                };
                script.onerror = (error) => {
                    console.error('XLSX库加载失败:', error);
                    reject(new Error('XLSX库文件加载失败'));
                };
                document.head.appendChild(script);
            });
        }

        function log(message, isError = false) {
            const resultDiv = document.getElementById('result');
            const className = isError ? 'result error' : 'result success';
            resultDiv.className = className;
            resultDiv.innerHTML = message;
            console.log(message);
        }

        async function testXLSXLoad() {
            try {
                const XLSX = await loadXLSX();
                log(`✅ XLSX库加载成功！<br>版本: ${XLSX.version || '未知'}<br>可用方法: ${Object.keys(XLSX.utils).length}个工具方法`);
            } catch (error) {
                log(`❌ 测试XLSX库时出错: ${error.message}`, true);
                console.error(error);
            }
        }

        async function testSimpleExport() {
            try {
                const XLSX = await loadXLSX();

                // 创建简单数据
                const data = [
                    ['姓名', '年龄'],
                    ['张三', 25],
                    ['李四', 30]
                ];

                // 创建工作簿和工作表
                const workbook = XLSX.utils.book_new();
                const worksheet = XLSX.utils.aoa_to_sheet(data);
                
                // 添加工作表到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, 'SimpleTest');
                
                // 使用Blob方式导出
                const fileName = `simple_test_${Date.now()}.xlsx`;
                const workbookOutput = XLSX.write(workbook, {
                    bookType: 'xlsx',
                    type: 'array'
                });
                
                const blob = new Blob([workbookOutput], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', fileName);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
                
                log(`✅ 简单导出测试成功！<br>文件名: ${fileName}<br>数据行数: ${data.length}`);
            } catch (error) {
                log(`❌ 简单导出测试失败: ${error.message}<br>错误详情: ${error.stack}`, true);
                console.error('Simple export error:', error);
            }
        }

        async function testComplexExport() {
            try {
                const XLSX = await loadXLSX();

                // 从表格获取数据
                const table = document.getElementById('testTable');
                const headers = Array.from(table.querySelectorAll('thead th')).map(th => th.textContent.trim());
                const rows = Array.from(table.querySelectorAll('tbody tr'));
                
                const tableData = [headers];
                
                rows.forEach(row => {
                    const rowData = Array.from(row.querySelectorAll('td')).map(td => {
                        const content = td.textContent.trim();
                        // 尝试转换数字
                        if (!isNaN(content) && content !== '') {
                            return parseFloat(content);
                        }
                        return content;
                    });
                    tableData.push(rowData);
                });

                // 创建工作簿
                const workbook = XLSX.utils.book_new();
                const worksheet = XLSX.utils.aoa_to_sheet(tableData);
                
                // 设置列宽
                worksheet['!cols'] = headers.map(header => ({ 
                    width: Math.max(header.length * 1.2, 12) 
                }));
                
                // 添加工作表
                XLSX.utils.book_append_sheet(workbook, worksheet, 'ComplexTest');
                
                // 使用Blob方式导出
                const fileName = `complex_test_${Date.now()}.xlsx`;
                const workbookOutput = XLSX.write(workbook, {
                    bookType: 'xlsx',
                    type: 'array'
                });
                
                const blob = new Blob([workbookOutput], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', fileName);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
                
                log(`✅ 复杂导出测试成功！<br>文件名: ${fileName}<br>表头: ${headers.join(', ')}<br>数据行数: ${tableData.length - 1}`);
            } catch (error) {
                log(`❌ 复杂导出测试失败: ${error.message}<br>错误详情: ${error.stack}`, true);
                console.error('Complex export error:', error);
            }
        }

        // 页面加载时自动测试XLSX库
        window.onload = function() {
            testXLSXLoad();
        };
    </script>
</body>
</html> 